<template>
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <div class="w-full">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane
              :label="item.channelName"
              :name="item.id"
              v-for="item in tabList"
              :key="item"
            ></el-tab-pane>
          </el-tabs>
        </div>
        <el-input
          v-model.trim="form.account"
          placeholder="账号名"
          clearable
          class="w-50"
        />
        <el-input
          v-model.trim="form.attribution"
          placeholder="户主"
          clearable
          class="w-50"
        />
        <VSelectPlus
          v-model="form.principalId"
          placeholder="主体名称"
          class="w-50"
          url="/accountPrincipal/options"
        />
        <VSelects
          v-model="form.state"
          placeholder="状态"
          class="w-50"
          :dataSourse="optionsData?.account_state || []"
        />
        <VSelects
          v-model="form.authorizeState"
          placeholder="授权状态"
          class="w-50"
          :dataSourse="optionsData?.account_authorize_state || []"
        />
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions" />
      </template>
    </VTable>
    <Add
      v-model="addVisible"
      :title="addTitle"
      :data="addData"
      :optionsData="optionsData"
      @refresh="refresh"
      @close="addData = null"
    />
    <Details
      v-model="detailsVisible"
      :id="detailsId"
      :accountId="detailsAccountId"
      title="子账号详情"
      :disabled="false"
      @refresh="refresh"
      @close="
        detailsId = null;
        detailsAccountId = null;
      "
    />
    <VLog
      v-model="logVisible"
      :autoLoad="false"
      :module="1"
      :id="logId"
      @close="logId = ''"
    />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { getAccountList, stateAccount, delAccount } from "./api.js";
import Add from "./add/index.vue";
import Details from "./details/index.vue";
import { getChannelList } from "@/views/base/channel/api.js";
import { useEnumSelect } from "@/hooks/index.js";
import { handleLink } from "@/utils/tools.js";
import { baseAuthList } from "@/Auth/base.js";
const { proxy } = getCurrentInstance();
const tableRef = ref();
const activeName = ref("");
const tabList = ref([]);
const { options: optionsData } = useEnumSelect({
  params: ["account_authorize_state", "account_state", "account_type"],
});
const getChannel = async () => {
  const { data } = await getChannelList({
    pageNum: 1,
    pageSize: 100,
  });

  data.forEach((item) => {
    item.id = item.id.toString();
  });
  activeName.value = data[0]?.id;
  let list = data.filter((item) => item.state.value === 1);
  tabList.value = list;
  const form = tableRef.value.getForm();
  // tableRef.value.setForm({ ...form, accountChannelId: activeName.value });
  tableRef.value.query();
};
getChannel();
const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    {
      type: "checkbox",
      width: 50,
      fixed: "left",
    },
    {
      title: "ID",
      field: "id",
      width: 180,
    },
    {
      title: "账号类型",
      field: "account",
      width: 100,
      slots: {
        default: ({ row }) => {
          return <div>{row?.accountType?.label}</div>;
        },
      },
    },
    {
      title: "账号",
      field: "account",
      width: 200,
    },
    {
      title: "户主",
      field: "attribution",
      minWidth: 100,
    },
    {
      title: "公司主体",
      field: "principalName",
      minWidth: 100,
    },
    {
      title: "登录链接",
      field: "loginUri",
      minWidth: 100,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-button
                type="primary"
                link
                onClick={() => handleLink(row?.loginUri)}
              >
                {row?.loginUri || "-"}
              </el-button>
            </div>
          );
        },
      },
    },
    {
      title: "子账号数量",
      field: "subAccountsNumber",
      width: 100,
    },
    {
      title: "子账号详情",
      width: 100,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-button
                type="primary"
                link
                onClick={() => handleCheck(row.id)}
              >
                查看
              </el-button>
            </div>
          );
        },
      },
    },
    {
      title: "状态",
      field: "state",
      width: 80,
      slots: {
        default: ({ row }) => {
          return <statusRender code={row.state} />;
        },
      },
    },
    {
      title: "授权状态",
      field: "authorizeState",
      width: 80,
      slots: {
        default: ({ row }) => {
          return <statusRender code={row.authorizeState} />;
        },
      },
    },
    {
      title: "备注",
      field: "remark",
      width: 160,
    },
    {
      title: "操作",
      width: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {[baseAuthList.account.edit] ? (
                <el-button type="primary" link onClick={() => handleAdd(row)}>
                  编辑
                </el-button>
              ) : (
                ""
              )}
              {[baseAuthList.account.delete] ? (
                <el-button
                  type="danger"
                  link
                  onClick={() => handleDelete(row.id)}
                >
                  删除
                </el-button>
              ) : (
                ""
              )}
              {[baseAuthList.account.log] ? (
                <el-button
                  type="primary"
                  link
                  onClick={() => handleLog(row.id)}
                >
                  日志
                </el-button>
              ) : (
                ""
              )}
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        let params = {
          ...form,
          accountChannelId: activeName.value,
        };
        if (!params.accountChannelId) {
          return Promise.resolve({
            data: [],
            total: 0,
          });
        }
        return getAccountList({ ...params, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});

const logVisible = ref(false);
const logId = ref("");
const handleLog = (item) => {
  logId.value = item;
  logVisible.value = true;
};

// 切换状态
const handleClick = (tab, even) => {
  activeName.value = tab.props.name;
  const form = tableRef.value.getForm();
  tableRef.value.setForm({ ...form, accountChannelId: tab.props.name });
  tableRef.value.query();
};

const addVisible = ref(false);
const addData = ref(null);
const addTitle = ref("新增");
const handleAdd = (data) => {
  const channel = tabList.value.find((item) => item.id === activeName.value);
  const channelData = {
    accountChannelId: activeName.value,
    accountChannelName: channel?.channelName,
    apiChannelType: channel?.apiChannelType?.value,
    accountChannelType: channel?.accountChannelType?.value,
  };
  const form = Object.assign(
    {},
    {
      ...data,
      accountType: data?.accountType?.value,
      apiChannelType: data?.apiChannelType?.value,
    },
    channelData
  );
  addVisible.value = true;
  addData.value = form || null;
  addTitle.value = data?.id ? "编辑" : "添加账号";
};

const handleDelete = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除
        <span class="text-[#3366F1] px-[4px]">{1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await delAccount({ id });
          if (code !== 200) return ElMessage.success(message);
          ElMessage.success("删除成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const handelStatus = (name, en) => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  const handle = {
    enable: async () => {
      try {
        const { code, message } = await stateAccount({ ids, state: 1 });
        if (code !== 200) return;
        ElMessage.success("启用成功!");
        refresh();
      } catch (error) {}
    },
    disabled: async () => {
      try {
        const { code, message } = await stateAccount({ ids, state: 0 });
        if (code !== 200) return;
        ElMessage.success("禁用成功!");
        refresh();
      } catch (error) {}
    },
    sync: () => {
      // api.sync().then(res => {
      //   query()
      //   ElMessage({ type: 'success', message: '操作成功!' })
      // }).finally(closeLoading)
    },
  };
  // handle[name]();
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认{en}
        <span class="text-[#3366F1] px-[4px]">{ids.length || 1}</span>
        条数据？
      </p>
    ),
    tips:
      en == "停用"
        ? `注意：${en}后，系统将不在获取资金流水,绑定店铺,其他模块无法获取该账号信息`
        : null,

    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await handle[name]();
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

//查看
const detailsVisible = ref(false);
const detailsId = ref(null);
const detailsAccountId = ref(null);
const handleCheck = (val) => {
  detailsId.value = activeName.value;
  detailsAccountId.value = val;
  detailsVisible.value = true;
};
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

// 创建 BroadcastChannel 实例
const channel = new BroadcastChannel("my_channel");

// 监听消息
channel.onmessage = (event) => {
  console.log("Received message:", event.data);
};
const actions = [
  {
    label: "添加账号",
    type: "primary",
    icon: "add1",
    fn: () => handleAdd(null),
    permission: [baseAuthList.account.add],
  },
  {
    label: "同步账号数据",
    type: "primary",
    fn: () => handleSync("sync", "同步账号数据"),
    permission: [baseAuthList.account.sync],
  },
  {
    label: "启用",
    icon: "state_enable",
    iconStyle: {
      color: "var(--main-color)",
    },
    fn: () => handelStatus("enable", "启用"),
    permission: [baseAuthList.account.enable],
  },
  {
    label: "停用",
    icon: "state_disabled",
    iconStyle: {
      color: "var(--info-color)",
    },
    fn: () => handelStatus("disabled", "停用"),
    permission: [baseAuthList.account.disabled],
  },
];
</script>
<style lang="scss" scoped>
:deep(.vx-table__form-content) {
  padding-top: 0;
}
:deep(.el-tabs__header) {
  margin: 0;
}
</style>
